package com.sms.fileupload;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.sms.DB.ConnectDB;
import com.sms.DB.OperateDB;

public class NewTask {
	// 添加新的项目时进行数据的插入，成功返回true
	public boolean insertData(String level, String proID, String content, String fromID, List<String> toID, String deadline, List<Map> appendFile) {
		String sql = "";

		boolean isSuccess = true;
		
		Connection conn = ConnectDB.getConnection();
		boolean autoCommit;
		try {
			autoCommit = conn.getAutoCommit();
			conn.setAutoCommit(false);// 取消自动提交

			// 向taskinfo表插入数据
			sql = "insert into taskinfo values(null, ?, ?, '个人任务', ?, ?, '', now(), ?, '0', '0')";
			List<Object> tlist = new ArrayList<Object>();
			tlist.add(level);
			tlist.add(proID);
			tlist.add(content);
			tlist.add(fromID);
			tlist.add(deadline);
			OperateDB.setList(tlist);
			int tn = OperateDB.getGeneratedKey(sql);

			// System.out.println(tn);
			if (tn == 0) { // 插入taskinfo不成功
				isSuccess = false;
			} else {
				if(toID != null && toID.size() > 0) {
					for (int i = 0; i < toID.size(); i++) {
						String toid = toID.get(i);
							sql = "insert into taskmember values(?, ?)";
							List<Object> gmlist = new ArrayList<Object>();
							gmlist.add(tn);
							gmlist.add(toid);
							OperateDB.setList(gmlist);
							if (!OperateDB.insert(sql)) {
								isSuccess = false;
								break;
							} 
					}
				} else {
					isSuccess = false;
				}
				
				if(isSuccess) {
					if (appendFile == null || appendFile.size() < 1) {// 没有添加附件时
						//System.out.println("没有附件");
						isSuccess = true;
					} else {// 有附件
						for (int i=0; i<appendFile.size(); i++) {
							Map<String, String> map = new HashMap<String, String>();
							map = (Map<String, String>)appendFile.get(i);
							String fileName = map.get("fileName").toString();
							String saveName = map.get("saveName").toString();
							// 向appendinfo表插入数据
							sql = "insert into appendinfo values('个人任务', ?, ?, ?)";
							List<Object> alist = new ArrayList<Object>();
							alist.add(tn);
							alist.add(fileName);
							alist.add(saveName);
							
							OperateDB.setList(alist);
							if (OperateDB.insert(sql)) {// 插入附件表是否成功
								sql = "update taskinfo set isappend = '1' where taskid = "
										+ tn;
								if (OperateDB.update(sql) > 0) {
									isSuccess = true;
								} else {
									isSuccess = false;
								}
							} else {
								isSuccess = false;
							}
						}// for结束
					}
				}
				
			}

			if (isSuccess) {
				conn.commit();// 手动提交
			} else {
				conn.rollback();
			}
			conn.setAutoCommit(autoCommit);// 恢复现场
		} catch (SQLException e) {
			e.printStackTrace();
			isSuccess = false;
		} finally {
			OperateDB.close(conn);
		}

		return isSuccess;
	}
}
